package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelVideoAdapter;
import flc.ast.databinding.ActivityPlayLocalBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class PlayLocalActivity extends BaseAc<ActivityPlayLocalBinding> {

    private SelVideoAdapter selVideoAdapter;
    private int oldPosition = 0, kind = 1;
    private String selPath = "";
    private Dialog myImportDialog,myDeleteDialog;
    private TextView dialogPublic,dialogPrivacy;

    @Override
    protected int onCreate() {
        return R.layout.activity_play_local;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPlayLocalBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvPlayLocalList.setLayoutManager(new GridLayoutManager(mContext, 3));
        selVideoAdapter = new SelVideoAdapter();
        mDataBinding.rvPlayLocalList.setAdapter(selVideoAdapter);
        selVideoAdapter.setOnItemClickListener(this);
        mDataBinding.tvPlayLocalImport.setOnClickListener(this);
        mDataBinding.llPlayLocalBottom.setOnClickListener(null);
        mDataBinding.ivPlayLocalDelete.setOnClickListener(this);
        importDialog();
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvPlayLocalImport:
                if (selPath.isEmpty()){
                    ToastUtils.showShort(R.string.please_sel_import_video);
                    return;
                }
                myImportDialog.show();
                break;
            case R.id.ivDialogImportCancel:
                myImportDialog.dismiss();
                break;
            case R.id.ivDialogImportConfirm:
                if (kind == 1) {
                    saveToAlbum(Content.Album_Public);
                } else if (kind == 2) {
                    saveToAlbum(Content.Album_Privacy);
                }
                myImportDialog.dismiss();
                break;
            case R.id.tvDialogImportPublic:
                clearSelection();
                dialogPublic.setBackgroundResource(R.drawable.shape_import);
                dialogPublic.setTypeface(Typeface.DEFAULT_BOLD);
                kind=1;
                break;
            case R.id.tvDialogImportPrivacy:
                clearSelection();
                dialogPrivacy.setBackgroundResource(R.drawable.shape_import);
                dialogPrivacy.setTypeface(Typeface.DEFAULT_BOLD);
                kind=2;
                break;
            case R.id.ivPlayLocalDelete:
                if (selPath.isEmpty()){
                    ToastUtils.showShort(R.string.please_sel_delete_video);
                    return;
                }
                myDeleteDialog.show();
                break;
            case R.id.ivDialogDeleteCancel:
                 myDeleteDialog.dismiss();
                 break;
            case R.id.ivDialogDeleteConfirm:
                deleteVideo();
                myDeleteDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        selVideoAdapter.getItem(oldPosition).setChecked(false);
        selVideoAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        selVideoAdapter.getItem(position).setChecked(true);
        selVideoAdapter.notifyItemChanged(position);
        selPath = selVideoAdapter.getItem(position).getPath();
    }

    @Override
    protected void initData() {
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_storage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        mDataBinding.rvPlayLocalList.setVisibility(View.GONE);
                        mDataBinding.llPlayLocalNoData.setVisibility(View.GONE);
                    }
                }).request();
    }

    //获取视频和图片数据
    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(getApplicationContext(), PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    selVideoAdapter.setList(selectMediaEntities);
                    mDataBinding.rvPlayLocalList.setVisibility(View.VISIBLE);
                    mDataBinding.llPlayLocalNoData.setVisibility(View.GONE);
                    mDataBinding.llPlayLocalBottom.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.rvPlayLocalList.setVisibility(View.GONE);
                    mDataBinding.llPlayLocalNoData.setVisibility(View.VISIBLE);
                    mDataBinding.llPlayLocalBottom.setVisibility(View.GONE);
                }
            }
        });
    }

    //导入到相册
    private void saveToAlbum(String path) {
        showDialog(getString(R.string.import_album_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                //保存到对应相册
                String resultFile = FileUtil.generateFilePath(path, ".mp4");
                FileUtils.copy(selPath, resultFile);
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                dismissDialog();
                ToastUtils.showShort(R.string.import_suc);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                },500);
            }
        });
    }

    //适配android11以上删除相册文件方式
    private void deleteVideo() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            List<Uri> uris = new ArrayList<>(); // 这里存放所有需要删除的图片的uri
            for (int i = 0; i < selVideoAdapter.getValidData().size(); i++) {
                if (selVideoAdapter.getItem(i).isChecked()) {
                    uris.add(Uri.parse(selVideoAdapter.getItem(i).getUri()));
                }
            }
            PendingIntent pi = MediaStore.createDeleteRequest(getContentResolver(), uris);
            try {
                startIntentSenderForResult(pi.getIntentSender(), REQUEST_CODE_DELETE_IMAGE, null, 0, 0, 0);
            } catch (IntentSender.SendIntentException e) {
                Log.e("TAG", "startIntentSender error:" + e.toString());
            }
        } else {
            for (int i = 0; i < selVideoAdapter.getValidData().size(); i++) {
                if (selVideoAdapter.getItem(i).isChecked()) {
                    getContentResolver().delete(Uri.parse(selVideoAdapter.getItem(i).getUri()), null, null);
                    selVideoAdapter.remove(selVideoAdapter.getItem(i));
                }
            }
            selVideoAdapter.notifyDataSetChanged();
        }
    }

    //删除相册图片
    public final int REQUEST_CODE_DELETE_IMAGE = 1000;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_DELETE_IMAGE) {
            if (resultCode == Activity.RESULT_OK) {
                for (int i = 0; i < selVideoAdapter.getValidData().size(); i++) {
                    if (selVideoAdapter.getItem(i).isChecked()) {
                        selVideoAdapter.remove(selVideoAdapter.getItem(i));
                    }
                }
                selVideoAdapter.notifyDataSetChanged();
                Log.e("TAG", "onActivityResult: " );
            }
        }
    }

    //导入弹框
    private void importDialog() {
        myImportDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_import, null);
        myImportDialog.setContentView(inflate);
        myImportDialog.setCancelable(true);
        //获取当前Activity所在的窗体
        Window dialogWindow = myImportDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialogPublic = inflate.findViewById(R.id.tvDialogImportPublic);
        dialogPrivacy = inflate.findViewById(R.id.tvDialogImportPrivacy);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogImportCancel);
        ImageView dialogConfirm = inflate.findViewById(R.id.ivDialogImportConfirm);
        dialogPublic.setOnClickListener(this);
        dialogPrivacy.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);
        dialogConfirm.setOnClickListener(this);
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        //获取当前Activity所在的窗体
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogConfirm = inflate.findViewById(R.id.ivDialogDeleteConfirm);
        ImageView dialogCancel= inflate.findViewById(R.id.ivDialogDeleteCancel);
        dialogConfirm.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);
    }

    private void clearSelection(){
        dialogPublic.setTypeface(Typeface.DEFAULT);
        dialogPublic.setBackground(null);
        dialogPrivacy.setTypeface(Typeface.DEFAULT);
        dialogPrivacy.setBackground(null);
    }

}